﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Configuration;
using BLL;
using Model;
using Common;

namespace WebPortal
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                //new { controller = "Account", action = "LogOn", id = UrlParameter.Optional }
                new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            //Application.Add("WebServiceAudit", new List<WebPortal.Models.WebServiceAudit>());

            //if (Application["RunTask"] == null)
            //{
            //    Application.Add("RunTask", "Begin");
            //    string ts = ConfigurationManager.AppSettings["Timer"];
            //    foreach (DBDeploy db in SysMenuBLL.GetDBList())//取数据库列表
            //    {
            //        System.Timers.Timer timer = new System.Timers.Timer();
            //        timer.Interval = int.Parse(ts) * 1000;  //设置计时器事件间隔执行时间
            //        LoginInfo loginInfos = new LoginInfo();
            //        loginInfos.DBName = db.DBName;
            //        ETLTaskBLL etlTaskBLL = new ETLTaskBLL(loginInfos);
            //        timer.Elapsed += new System.Timers.ElapsedEventHandler(etlTaskBLL.RunTask);
            //        timer.Enabled = true;
            //    }
            //}
        }

        protected void Application_End()
        {
            //GetResponseUrl();
        }
        /// <summary>
        /// 错误处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            Response.Write("操作失败，请检查提交的信息。");
            Response.End();
            //ExceptionHandlerStarter();
            //GetResponseUrl();
        }
        protected void GetResponseUrl()
        {
            try
            {
                System.Threading.Thread.Sleep(1000);
                string strUrl = ConfigurationManager.AppSettings["WebUrl"].ToString();
                System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
                System.Net.HttpWebResponse _HttpWebResponse = (System.Net.HttpWebResponse)_HttpWebRequest.GetResponse();
                System.IO.Stream _Stream = _HttpWebResponse.GetResponseStream();//得到回写的字节流
            }
            catch (Exception ex)
            {
                //string file = Server.MapPath("/Errors");
                //using (System.IO.StreamWriter sw = new System.IO.StreamWriter(file + "\\" + DateTime.Now.Day.ToString() + ".txt", true))
                //{
                //    sw.WriteLine(ex.Message);
                //}
            }
        }
        /// <summary>
        /// 异常处理
        /// </summary>
        public void ExceptionHandlerStarter()
        {
            String exMode = ConfigurationManager.AppSettings["ExceptionMode"];
            if (!String.IsNullOrEmpty(exMode) && string.Compare(exMode.ToLower(), "on") == 0)
            {
                string s = HttpContext.Current.Request.Url.ToString();
                HttpServerUtility server = HttpContext.Current.Server;
                if (server.GetLastError() != null)
                {
                    Response.Write("操作失败，请检查提交的信息。");
                    Response.End();
                    //Exception lastError = server.GetLastError();
                    //Application["LastError"] = lastError;
                    //int statusCode = HttpContext.Current.Response.StatusCode;
                    //string exceptionOperator = ConfigurationManager.AppSettings["ExceptionUrl"];
                    //try
                    //{

                    //    //if (!String.IsNullOrEmpty(exceptionOperator))
                    //    //{
                    //    //    exceptionOperator = new System.Web.UI.Control().ResolveUrl(exceptionOperator);
                    //    //    string url = string.Format("{0}?ErrorUrl={1}", exceptionOperator, server.UrlEncode(s));
                    //    //    string script = String.Format("<script language='javascript' type='text/javascript'>window.top.location='{0}';</script>", url);
                    //    //    Response.Write(script);
                    //    //    Response.End();
                    //    //}
                    //}
                    //catch (Exception)
                    //{
                    //}
                }
            }
        }

        public void Application_BeginRequest(object sender, EventArgs e)
        {
            ////检查登录信息
            //if (Request.Cookies["MDM_UserName"] == null && Request.Url.AbsoluteUri.ToLower().IndexOf(".asmx") == -1)
            //{
            //    List<string> list = new List<string>();
            //    list.Add("/account");
            //    list.Add("/images");
            //    list.Add("/res");
            //    list.Add("/script");
            //    string url = Request.Url.AbsolutePath.ToLower();
            //    if (url != "/" && list.FindIndex(o => { return url.StartsWith(o); }) == -1)
            //        Response.Redirect("/Account/LogOn");
            //}
            //检查sql注入
            //string rc = ConfigurationManager.AppSettings["RequestCheck"].ToString();
            //if (Convert.ToBoolean(rc))
            //{
            //    bool result = false;
            //    if (Request.RequestType.ToUpper() == "POST")
            //    {
            //        result = RequestCheck.ValidUrlPostData();//Post数据检查
            //    }
            //    else
            //    {
            //        result = RequestCheck.ValidUrlGetData();//Get数据检查
            //    }

            //    if (result)
            //    {
            //        Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            //        Response.Write("您提交的数据有非法字符，请检查后提交！");
            //        //Response.Write("<script>alert('您提交的数据有非法字符，请检查后提交！');window.histroy.back();<//script>");
            //        Response.End();
            //    }
            //}
        }
    }
}